/**
 * 
 */
package model;

import java.util.ArrayList;

import common.DataManager;
import common.ItemFactory;

import controller.Controller;

/**
 * @author Bill
 * 
 * The Store class keeps track of selecting items that
 * the player can buy.
 *
 */
public class Store {
	
	private boolean itemSelected = false;
	private String selectedItem = "";
	private Player player;
	private Map map;
	
	//an array of one of each type of item.
	private ArrayList<Item> buyableItems = new ArrayList<Item>();
	
	public Store( Player player , Map map){
		itemSelected = false;
		selectedItem = "";
		this.player = player;
		this.map = map;
		
		//fill up the buyableItem array with one item of each type
		for(int i = 0; i < DataManager.getManualWeaponIcons().size(); i++){
			buyableItems.add(ItemFactory.createItemFromImageName(DataManager.getManualWeaponIcons().get(i)));
		}
		for(int i = 0; i < DataManager.getAutomaticWeaponIcons().size(); i++){
			buyableItems.add(ItemFactory.createItemFromImageName(DataManager.getAutomaticWeaponIcons().get(i)));
		}
		for(int i = 0; i < DataManager.getDefensiveItemIcons().size(); i++){
			buyableItems.add(ItemFactory.createItemFromImageName(DataManager.getDefensiveItemIcons().get(i)));
		}
		for(int i = 0; i < DataManager.getUpgradeIcons().size(); i++){
			buyableItems.add(ItemFactory.createItemFromImageName(DataManager.getUpgradeIcons().get(i)));
		}
	}
	
	public boolean selectItem(String itemName){
		Item item = ItemFactory.createItemFromImageName(itemName);
		if(item.canBuy(player.getPoints())){
			itemSelected = true;
			selectedItem = itemName;
			if( item instanceof ManualWeapon || item instanceof Upgrade){
				System.out.println("BUYING A MANUAL WEAPON OR UPGRADE");
				deselectAndBuyItem();
			}
		}
		Controller.updateView();
		return item.canBuy(player.getPoints());
	}
	
	/**
	 * Our Items are bought when the item is deselected.
	 */
	public void deselectAndBuyItem(){
		Item item = ItemFactory.createItemFromImageName(selectedItem);
		player.buyItem( item.getCost() ); 
		if( item instanceof ManualWeapon ){
			player.getCargo().addAmmo(player.getCargo().getManualWeapon(selectedItem));
		}
		else if( item instanceof Upgrade ){
			Upgrade up = (Upgrade) item;
			up.setPlayer(player);
			up.setMap(map);
			up.applyUpgrade();
		}
		deselectItem();
	}
	
	public void deselectItem(){
		itemSelected = false;
		selectedItem = "";
		Controller.updateView();
	}

	public String getSelectedItem() {
		return selectedItem;
	}

	public boolean isItemSelected() {
		return itemSelected;
	}

	public ArrayList<Item> getBuyableItemsList(){
		return this.buyableItems;
	}
	
	public boolean playerCanBuyItem(Item item, Player player){
		if(item.getCost() > player.getPoints()) return false;
		else return true;
	}

}
